package com.cino.demos.sourceCode.AOPdemo;

import java.lang.reflect.Method;
import java.util.List;

public class MyMethodInvocation implements MethodInvocation {
    private final Object proxy;
    private final Object target;
    private final Method method;
    private final Object[] arguments;
    private final List<MethodInterceptor> interceptors;
    private int currentInterceptorIndex = -1; // 当前拦截器索引
    
    public MyMethodInvocation(Object proxy, Object target, Method method, Object[] arguments,
                            List<MethodInterceptor> interceptors) {
        this.proxy = proxy;
        this.target = target;
        this.method = method;
        this.arguments = arguments;
        this.interceptors = interceptors;
    }
    
    @Override
    public Object proceed() throws Throwable {
        // 所有拦截器都执行完了，调用真实方法 ⭐
        if (this.currentInterceptorIndex == this.interceptors.size() - 1) {
            System.out.println("  🔁 所有通知执行完毕，准备调用真实方法");
            return this.method.invoke(this.target, this.arguments); // 反射调用真实方法
        }
        
        // 依次执行拦截器
        this.currentInterceptorIndex++;
        MethodInterceptor interceptor = this.interceptors.get(this.currentInterceptorIndex);
        System.out.println("  🔁 执行第" + (this.currentInterceptorIndex + 1) + "个拦截器");
        return interceptor.invoke(this); // 递归调用
    }
    
    @Override
    public Object getThis() {
        return this.proxy;
    }
    
    @Override
    public Method getMethod() {
        return this.method;
    }
    
    @Override
    public Object[] getArguments() {
        return this.arguments;
    }
}